/**
 * @format
 * @Author: TC
 * @Date: 2023-10-23 19:09:41
 * @Last Modified by: TC
 * @Last Modified time: 2025-06-08 11:02:10
 */

import { EntityBase } from "db://assets/Script/Game/Entity/EntityBase";
import { app } from "../../App";
import { ICmdData } from "./CmdInterface";

export class CmdItem {
    private _entity: EntityBase = null;
    public get entity(): EntityBase {
        return this._entity;
    }
    private _uid: number = 0;
    private _frameCmdList: ICmdData[] = [];
    private _cb: (cmd: ICmdData) => void = null;
    // private _rdKey: Record<mBattleConst.EKeyboardCode, boolean> = [] as any;
    private _defaultCmd: ICmdData = null;

    constructor(entity: EntityBase, cb: (cmd: ICmdData) => void = null) {
        this._entity = entity;
        this.uid = this.entity.uid;
        app.inputMgr.add(this);
        if (cb) {
            this._cb = cb;
        }
    }

    // public get rdKey(): Record<mBattleConst.EKeyboardCode, boolean> {
    //     return this._rdKey;
    // }

    public set uid(uid: number) {
        this._uid = uid;
    }

    public get uid(): number {
        return this._uid;
    }

    /**
     * 设置默认命令
     * @param cmd
     */
    public setDefaultCmd(cmd: ICmdData): void {
        this._defaultCmd = cmd;
    }

    /**
     * 获取默认命令
     */
    private getDefaultCmd(): ICmdData {
        return this._defaultCmd;
    }

    /**
     * 输入命令
     * @param cmd
     */
    public inputCmd(cmd: ICmdData): void {
        this._frameCmdList.push(cmd);
    }

    /**
     * 输出命令
     * @returns
     */
    public outputCmd(): ICmdData {
        let cmd = this._frameCmdList.pop() || this.getDefaultCmd();
        // if(cmd)console.log(cmd.code)
        this._frameCmdList.length = 0;
        return cmd;
    }

    public clear(): void {
        // this._frameCmdList.length = 0;
        // this.execute()
    }

    /**
     * 执行命令
     */
    public execute(): void {
        let cmd = this.outputCmd();
        if (!cmd) {
            return;
        }
        this._cb && this._cb(cmd);
    }

    public removeCode(keyCode: number): void {
        for (let i = this._frameCmdList.length - 1; i >= 0; i--) {
            if (this._frameCmdList[i].code == keyCode) {
                this._frameCmdList.splice(i, 1);
            }
        }
    }

    /**
     * 刷新
     */
    public tick(): void {
        // let cmd = this.outputCmd();
    }
}
